package com.ta.gulimall.product.controller.redisson;

import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SemaphoreController {
    @Autowired
    RedissonClient redissonClient;

    /**
     * 信号灯：设置总人数
     * @param count
     * @return
     */
    @GetMapping("/addPermits/{count}")
    public String addPermits(@PathVariable("count") Long count) {
        RSemaphore semaphore = redissonClient.getSemaphore("semaphore");
        semaphore.addPermits(10);

        return "设置上线总人数" + count;
    }

    /**
     * 信号灯：尝试获取+1
     * @return
     */
    @GetMapping("/tryAcquire")
    public String tryAcquire() {
        RSemaphore semaphore = redissonClient.getSemaphore("semaphore");
        boolean tryAcquire = semaphore.tryAcquire();
        if (tryAcquire){
            return "上线了";
        }else{
            return "服务器阻塞中：等待上线";
        }
    }

    /**
     * 信号灯：获取+1
     * @return
     * @throws InterruptedException
     */
    @GetMapping("/acquire")
    public String acquire() throws InterruptedException {
        RSemaphore semaphore = redissonClient.getSemaphore("semaphore");
        semaphore.acquire();

        return "上线了";
    }

    /**
     * 信号灯：释放-1
     * @return
     */
    @GetMapping("/release")
    public String release() {
        RSemaphore semaphore = redissonClient.getSemaphore("semaphore");
        semaphore.release();

        return "下线了";
    }

}
